package com.wyl.learn02;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.wyl.config.RabbitMqConfig;

import java.util.Scanner;

public class Producer02 {
    public static final String TASK_QUEUE_NAME_DURABLE = "ack_queue_durable";
    public static final String TASK_QUEUE_NAME_TRANSIENT = "ack_queue_transient";

    public static void main(String[] argv) throws Exception {
        //创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMqConfig.IP);
        factory.setUsername(RabbitMqConfig.USERNAME);
        factory.setPassword(RabbitMqConfig.PASSWORD);
        //channel 实现了自动 close 接口 自动关闭 不需要显示关闭
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明持久化队列
            // 开启队列持久化：1.队列设置为持久化
            channel.queueDeclare(TASK_QUEUE_NAME_DURABLE, true, false, false,null);
            // 声明非持久化队列
            channel.queueDeclare(TASK_QUEUE_NAME_TRANSIENT, false, false, false,null);

            Scanner sc = new Scanner(System.in);
            System.out.println("请输入信息");
            while (sc.hasNext()) {
                String message = sc.nextLine();
                // 消息持久化
                // 开启队列持久化：2.发布消息的时候设置为持久化
                channel.basicPublish("", TASK_QUEUE_NAME_DURABLE, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes("UTF-8"));
                // 发布非持久化消息
                channel.basicPublish("", TASK_QUEUE_NAME_TRANSIENT, null, message.getBytes("UTF-8"));
                System.out.println("生产者发出消息" + message);
            }
        }
    }
}